package com.yuhao.init.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuhao.init.common.BaseResponse;
import com.yuhao.init.common.ErrorCode;
import com.yuhao.init.common.ResultUtils;
import com.yuhao.init.config.MinioConfig;
import com.yuhao.init.constant.FileConstant;
import com.yuhao.init.exception.BusinessException;
import com.yuhao.init.mapper.WallPaperClassifyMapper;
import com.yuhao.init.model.dto.classify.RequestClassify;
import com.yuhao.init.model.entity.WallPaperClassify;
import com.yuhao.init.model.vo.ClassifyNamesVo;
import com.yuhao.init.model.vo.PageResultVo;
import com.yuhao.init.service.WallPaperClassifyService;
import com.yuhao.init.utils.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: yuhao
 * @Date: 2024/5/2 10:11
 */

@RestController
@RequestMapping("/classify")
@Slf4j
public class WallPaperClassifyController {

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioConfig minioConfig;

    @Resource
    private WallPaperClassifyMapper wallPaperClassifyMapper;

    @Resource
    private WallPaperClassifyService wallPaperClassifyService;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse uploadFile(@RequestPart("file") MultipartFile multipartFile) throws IOException {
        //校验图片是否符合规范
        Boolean validFile = validFile(multipartFile);
        if (!validFile) return ResultUtils.error(ErrorCode.OPERATION_ERROR, "文件不符合要求");
        String objectName = minioUtil.upload(multipartFile, "classify");
        if (null == objectName) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "上传失败");
        }
        String picurl = FileConstant.COS_HOST + "/" + minioConfig.getBucketName() + "/" + objectName;
        log.info("上传成功，url为:{}", picurl);
        return ResultUtils.success(picurl, "上传成功");
    }

    @PostMapping("/add")
    public BaseResponse addWallPaperClassifyVo(@RequestBody RequestClassify requestClassify) {

        if (requestClassify == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "数据为空");
        }
        if (StringUtils.isBlank(requestClassify.getPicurl()) || StringUtils.isBlank(requestClassify.getName())) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "图片或者分类名称不能为空");
        }
        WallPaperClassify wallPaperClassify = new WallPaperClassify();
        wallPaperClassify.setName(requestClassify.getName());
        wallPaperClassify.setSort(requestClassify.getSort());
        wallPaperClassify.setPicurl(requestClassify.getPicurl());
        wallPaperClassify.setRecommend(requestClassify.getRecommend());
        int insert = wallPaperClassifyMapper.insert(wallPaperClassify);
        return ResultUtils.success(null, insert > 0 ? "添加成功" : "添加失败");
    }

    @GetMapping("/list/page")
    public BaseResponse<PageResultVo<WallPaperClassify>> listWallPaperClassify(Long pageSize, Long currentPage, Boolean select) {
        /**
         * 如果select为true，不在进行分页查询
         */
        Long total = wallPaperClassifyMapper.selectCount(null);
        if (BooleanUtils.isTrue(select)) {
            //推荐为真，就不在分页查询了
            LambdaQueryWrapper<WallPaperClassify> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WallPaperClassify::getRecommend, select);
            List<WallPaperClassify> records = wallPaperClassifyMapper.selectList(lambdaQueryWrapper);
            return ResultUtils.success(new PageResultVo<>(total,records));

        }
        if (pageSize == null || currentPage == null || pageSize.intValue()<0 || currentPage.intValue()<0) {
            pageSize = 10L;
            currentPage = 1L;
        }
        Page<WallPaperClassify> page = wallPaperClassifyMapper.selectPage(new Page<>(currentPage, pageSize), null);
        List<WallPaperClassify> records = page.getRecords();
        return ResultUtils.success(new PageResultVo<>(total,records));
    }

    @GetMapping("/get")
    public BaseResponse getWallPaperClassifyVoById(int id) {
        if (id == 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        WallPaperClassify wallPaperClassify = wallPaperClassifyMapper.selectById(id);
        return ResultUtils.success(wallPaperClassify);
    }

    @PostMapping("/edit")
    public BaseResponse editWallPaperClassify(@RequestBody WallPaperClassify wallPaperClassify) {
        if (wallPaperClassify == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        int status = wallPaperClassifyMapper.updateById(wallPaperClassify);
        System.out.println("status" + status);
        return ResultUtils.success(null, "更新成功");
    }


    @DeleteMapping("/delete")
    public BaseResponse deleteWallPaperClassifyVo(Long id) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }
        int i = wallPaperClassifyMapper.deleteById(id);
        return ResultUtils.success(null, i > 0 ? "删除成功" : "删除失败");
    }

    @GetMapping("/getClassifyNames")
    public BaseResponse getClassifyNames() {
        List<ClassifyNamesVo> classifyName = wallPaperClassifyService.getClassifyName();
        return ResultUtils.success(classifyName);
    }

    /**
     * 校验文件
     * @param multipartFile
     */
    private Boolean validFile(MultipartFile multipartFile) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        System.out.println("文件尺寸:" + fileSize);
        if (fileSize > 3 * 1024 * 1024L) {
            return false;
        }
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        return Arrays.asList("jpg", "png", "jpeg").contains(fileSuffix);
    }


}
